package com.example.myfirstapplication.asyncTask

import android.os.AsyncTask
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import com.example.myfirstapplication.data.Weather_Data
import com.example.myfirstapplication.utils.Tag
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.IOException

class CommonTask : AsyncTask<String, Int, String>() {
    var progressBar: ProgressBar? = null
    var data: String? = null
    var url: String? = null
    private var mCallbackHandler: ((String) -> Unit?)? = null

    fun setCallbackHandler(_handler: ((String) -> Unit)) {
        mCallbackHandler = _handler
    }

    //读数据前调用
    override fun onPreExecute() {
        super.onPreExecute()
        Log.i(Tag, "异步任务执行前显示Loading")
        progressBar?.visibility = View.VISIBLE
    }

    //后台运行的子线程
    override fun doInBackground(vararg params: String?): String? {
        Log.i(Tag, "异步任务执行开始了！")
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url!!).build()
        val call = okHttpClient.newCall(request)
        try {
            val response = call.execute()
            if (response.isSuccessful) {
                data = response.body!!.string()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        Log.i(Tag, "异步任务执行结束了！")
        return data
    }

    //数据读完之后调用
    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        Log.i(Tag, "异步任务执行结束隐藏Loading")
        progressBar?.visibility = View.GONE
        if (result != null) {
            mCallbackHandler?.invoke(result)
            Log.i(Tag, "你处理后的数据在这里：${result.toString()}")
        }
    }
}